import React, { useCallback, useEffect } from 'react';
import { connect } from 'react-redux'
import styled from 'styled-components'
import SearchCity from './components/searchCity'
import { actions } from './module'
import qs from 'qs'
// import querystring from 'querystring'
// import SearchCity from './components/searchCity'

interface IProps {
  index: {
    cityList?: any[],
    from: string,
    to: string
  },
  dispatch?: any,
  history: any
}

const SelectCity: React.FC<IProps> = (props) => {
  const { index: { cityList, from, to }, dispatch } = props;
  const alphabet = Array.from(new Array(26), (ele, index) => {
    return String.fromCharCode(65 + index);
  });

  useEffect(() => {


    const action = actions.getCityData()
    dispatch(action)
  }, [])

  const toAlpha = useCallback((alpha) => {
    document.querySelector(`[data-city=${alpha}]`)?.scrollIntoView(true)
  }, [])

  const selectCity = (val: string) => {
    let str = props.history.location.search.split('?')[1];
    let dir: any = qs.parse(str).dir;
    // console.log(city, 'city---------city')
    let action;
    if (dir === 'left') {
      action = actions.selectCity({ from: val, to, dir })
    } else {
      action = actions.selectCity({ from, to: val, dir })
    }
    dispatch(action)

    props.history.push('/index')
  }

  return <SelectCityWrapper className="select-city">
    <SearchCity></SearchCity>
    <div className="left">
      {
        cityList && cityList.map((item: any) => {
          return <ul key={item.title} data-city={item.title}>
            <li >{item.title}</li>
            {
              item.citys && item.citys.map((val: any) => {
                return <li key={val.name}
                  onClick={() => selectCity(val.name)}
                >{val.name}</li>
              })
            }
          </ul>
        })
      }
    </div>
    <ul className="right">
      {
        alphabet.map(alpha => {
          return <li key={alpha}
            onClick={() => toAlpha(alpha)}
          >{alpha}</li>
        })
      }
    </ul>
  </SelectCityWrapper>
}

export default connect((state) => {
  // console.log("state:", state)
  return { ...state }
}, (dispatch) => {
  return { dispatch }
})(SelectCity);


const SelectCityWrapper = styled.div`
  width: 100vw;
  height: 100vh;
  .right {
    position:fixed;
    right: 5px;
    top: 5px;
    li {
      width: 25px;
      height: 25px;
      border-radius: 5px;
      margin:3px;
      background: gold;
      text-align:center;
      line-height: center;
    }
  }
`;

